# coding=utf-8
# !/usr/bin/python
# by eaudouce
import sys, requests, time, json, re, urllib.parse
sys.path.append('..')
from lxml import etree
from base.spider import Spider
from pprint import pprint

class Spider(Spider):  # 元类 默认的元类 type
    site_name = 'xk_360吧'

    pub_url = 'https://360baty.com/'
    site_url = '' #https://www.360ba.co
    headers = {
        'Accept-Encoding': 'gzip, deflate',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36'
    }

    config = {
        'player': {},
        'class': [
            {'type_name':'热门', 'type_id':'0'},
            {'type_name':'全部', 'type_id':'1'},
            {'type_name':'足球', 'type_id':'2'},
            {'type_name':'篮球', 'type_id':'3'},
            {'type_name':'综合', 'type_id':'99'}
        ],
        'filter': {
            '2': [{
                'key': 'league_id',
                'name': '分类',
                'value': [{'n': i.split(',')[0], 'v': i.split(',')[1]} for i in '英超,36#西甲,31#意甲,34#德甲,8#法甲,11#欧冠,103#亚冠,192#中超,60'.split('#')]
            }],
            '3': [{
                'key': 'league_id',
                'name': '分类',
                'value': [{'n': i.split(',')[0], 'v': i.split(',')[1]} for i in 'NBA,1#CBA,5'.split('#')]
            }]
        }
    }

    def getSiteUrl(self):
        rsp = self.fetch(self.pub_url, headers=self.headers)
        root = self.html(self.cleanText(rsp.text))
        urls = root.xpath('//a[@class="backup"]/@href | //p[@class="perpetual"]/a/@href')
        url = ''
        for url in urls:
            rsp = requests.head(url, headers=self.headers)
            #print(url, rsp.status_code)
            if rsp.status_code == 200:
                break
        self.site_url = url.strip('/')
        return self.site_url

    def getName(self):
        return self.site_name

    def init(self, extend=''):
        pass

    def homeContent(self, filter):
        result = {'class': self.config['class']}
        if filter:
            result['filters'] = self.config['filter']
        return result

    def homeVideoContent(self):
        return {'list': []}

    def categoryContent(self, tid, pg, filter, extend):
        if '' == self.site_url:
            self.getSiteUrl()

        tid = str(tid)
        pg = int(pg)
        result = {
            'page': pg,
            'pagecount': 1,
            'limit': 99,
            'total': 99
        }

        if tid == '0':
            url = '{}/api/v3/new_index'.format(self.site_url)
            key = 'hot_matches'
        else:
            url = '{0}/api/web/live_lists/{1}?&supplement=0'.format(self.site_url, tid)
            if len(str(extend.get('league_id', ''))) > 0:
                url += '&league_id={}'.format(extend['league_id'])
            key = 'data'
        #print(url)
        videos = self.getVideos(url, key)

        result['list'] = videos
        return result

    def getVideos(self, url, key):
        headers = self.headers
        headers['Referer'] = self.site_url
        headers['Origin'] = self.site_url
        rsp = self.fetch(url, headers=headers)
        json_data = json.loads(rsp.text)
        #pprint(json_data)

        videos = []
        if 'data' not in json_data.keys() or key not in json_data['data'].keys():
            return videos

        for a in json_data['data'][key]:
            if a.get('tournament_id') and a.get('member_id'):
                vod_id = '{}_{}_{}_{}_{}'.format(a['tournament_id'], a['member_id'], a['type'], 0, self.site_url)
                vod_name = '{} {} VS {}'.format(a['league_name_zh'], a['home_team_zh'], a['away_team_zh'])
                vod_remarks = '直播' + time.strftime(' %H:%M', time.localtime(a['start_time_int'])) if a.get('start_time_int') else '中'
                vod_pic = self.genFullUrl(a['home_logo'], url)
            else:
                vod_id = '{}_{}_{}_{}_{}'.format(a['id'], '', '', 1, self.site_url)
                vod_name = a['title']
                vod_remarks = '回放'
                vod_pic = self.genFullUrl(a['cover'], url)
            if vod_pic.find(self.site_url) > -1:
                vod_pic = ''
            videos.append({
                'vod_id': vod_id,
                'vod_name': vod_name,
                'vod_pic': vod_pic,
                'vod_remarks': vod_remarks
            })
        return videos

    def detailContent(self, array):
        video_id, member_id, v_type, video_type, site_domain = array[0].split('_', 4)
        if video_type == '0':
            url = '{}/api/web/live_lists/{}/detail/{}?member_id={}'.format(site_domain, v_type, video_id, member_id)
            referer = '{}/detail/{}/{}/{}'.format(site_domain, v_type, video_id, member_id)
        else:
            url = '{}/api/web/video_list/detail/{}'.format(site_domain, video_id)
            referer = '{}/reply/{}'.format(site_domain, video_id)

        headers = self.headers
        headers['Referer'] = referer
        headers['Origin'] = site_domain
        rsp = self.fetch(url, headers=headers)
        json_data = json.loads(rsp.text)['data']['detail']

        if video_type == '0':
            vod_name = '{} {} VS {}'.format(json_data['league_name_zh'], json_data['home_team_zh'], json_data['away_team_zh'])
            vod_remarks = json_data['match_time']
            vod_pic = self.genFullUrl(json_data['home_logo'], referer)
            ep_name = '直播'
            ep_url = json_data['stream']
        else:
            vod_name = json_data['title']
            vod_remarks = '@'+json_data['username']
            vod_pic = self.genFullUrl(json_data['cover'], referer)
            ep_name = '回放'
            ep_url = json_data['video_url']
        if vod_pic.find(site_domain) > -1:
            vod_pic = ''
        vod = {
            'vod_id': array[0],
            'vod_name': vod_name,
            'vod_pic': vod_pic,
            'vod_remarks': vod_remarks,
            'vod_content': '【{}】{} {}'.format(ep_name, vod_name, vod_remarks),
            'vod_play_from': self.site_name,
            'vod_play_url': '{}${}_{}'.format(ep_name, referer, ep_url)
        }

        result = {
            'list': [
                vod
            ]
        }
        return result

    def searchContent(self, key, quick):
        return {'list': []}

    def playerContent(self, flag, id, vipFlags):
        referer, url = id.split('_', 1)
        origin = '/'.join(referer.split('/')[:3])
        headers = self.headers
        headers['Referer'] = referer
        headers['Origin'] = origin
        result = {
            'parse': '0',
            'playUrl': '',
            'url': url,
            'header': headers
        }
        return result

    def loadVtt(self, url):
        pass

    def isVideoFormat(self, url):
        pass

    def manualVideoCheck(self):
        pass

    def localProxy(self, param):
        action = {}
        return [200, 'video/MP2T', action, '']

    def genFullUrl(self, url, page_url):
        url = url.strip()
        page_url = page_url.strip()
        result = urllib.parse.urlparse(page_url)
        if len(url) < 1:
            return url
        elif url.startswith('http://') or url.startswith('https://'):
            return url
        elif url.startswith('//'):
            return result.scheme + ':' + url
        elif url.startswith('/'):
            return result.scheme + '://' + result.netloc + url
        elif url.startswith('./'):
            return result.scheme + '://' + result.netloc + '/'.join(result.path.split('/')[:-1]).rstrip('/') + '/' + url[2:]
        elif url.startswith('../'):
            url_arr = url.split('../')
            pos = -len(url_arr)
            return result.scheme + '://' + result.netloc + '/'.join(result.path.split('/')[:pos]).rstrip('/') + '/' + url_arr[-1]
        else:
            return result.scheme + '://' + result.netloc + '/'.join(result.path.split('/')[:-1]).rstrip('/') + '/' + url
